package com.bonc.test.redisdemo.config;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.bonc.test.redisdemo.ctrl.UserController;
import com.bonc.test.redisdemo.dao.UserDao;
import com.bonc.test.redisdemo.entity.User;

@Component
public class RedisFlushConfig {

	private static final Logger log = LoggerFactory.getLogger(RedisFlushConfig.class);
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private RedisClient redisClient;
	
	/**
	 *  每天凌晨一点刷新缓存数据
	 */
//	@Scheduled(fixedRate=60 * 1000)
	@Scheduled(cron="0 0 1 * * ?")
	public void start(){
		flushDb();
		saveToRedis();
	}
	
	private void saveToRedis() {
		List<User> userList = userDao.findAll();
		log.info("获取userList的数据为" + JSON.toJSONString(userList));
		if(StringUtils.isEmpty(redisClient.getListData("userList", 0)))
		for (User user : userList) {
			redisClient.setListData("userList", JSON.toJSONString(user));
			redisClient.setValue("user" + user.getId(),  JSON.toJSONString(user));
		}
	}

	public String flushDb() {
		redisTemplate.execute((RedisCallback<Object>) connection -> {
			connection.flushDb();
			return null;
		});
		log.info("缓存已刷新");
		return "ok";
	}
}
